package com.sikulifang.bank.simulation.controller;

import com.sikulifang.bank.simulation.util.PathUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;


/**
 * 页面控制器
 *
 * @author zhoul
 * @since 2.0.0
 */
@Slf4j
@Controller
@RequiredArgsConstructor
public class IndexController {

    /**
     * 登录页
     */
    @GetMapping(value = "/login")
    @SuppressWarnings("all")
    public String login() {
        return "login";
    }

    /**
     * 获取模板文件
     *
     * @param request 请求
     */
    @GetMapping(value = {"", "/", "/tpl/**"})
    public void tpl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path;

        String requestUri = request.getRequestURI();
        if ("/".equals(requestUri)) {
            path = requestUri + "index";
        } else {
            path = requestUri.replace("/tpl", "");
        }
        path = "templates" + path;

        if (!path.endsWith(".vue")) {
            path = path + ".vue";
        }
        File file = PathUtil.getPath(path);
        String content = StreamUtils.copyToString(new FileInputStream(file), StandardCharsets.UTF_8);
        StreamUtils.copy(content, StandardCharsets.UTF_8, response.getOutputStream());
    }
}
